#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
配置管理工具，用于保存和加载应用配置
"""

import os
import json
import time

class Config:
    """配置管理类"""
    
    def __init__(self, config_file="config.json"):
        """
        初始化配置管理器
        
        Args:
            config_file: 配置文件路径
        """
        self.config_file = config_file
        self.config = self._load_config()
    
    def _load_config(self):
        """加载配置"""
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, "r", encoding="utf-8") as f:
                    return json.load(f)
            except Exception:
                return self._get_default_config()
        else:
            return self._get_default_config()
    
    def _get_default_config(self):
        """获取默认配置"""
        return {
            "download_path": os.path.join(os.path.expanduser("~"), "Downloads"),
            "history": []
        }
    
    def save(self):
        """保存配置"""
        try:
            with open(self.config_file, "w", encoding="utf-8") as f:
                json.dump(self.config, f, ensure_ascii=False, indent=2)
            return True
        except Exception:
            return False
    
    def get(self, key, default=None):
        """获取配置项"""
        return self.config.get(key, default)
    
    def set(self, key, value):
        """设置配置项"""
        self.config[key] = value
        return self.save()
    
    def add_history(self, url, title):
        """添加下载历史"""
        history = self.config.get("history", [])
        history.append({
            "url": url,
            "title": title,
            "time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        })
        # 限制历史记录数量
        if len(history) > 50:
            history = history[-50:]
        self.config["history"] = history
        return self.save()